package com.itheima.web;

import com.itheima.constant.RedisConstant;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.utils.AliyunUtils;
import com.itheima.utils.UploadUtils;
import com.itheima.service.SetmealService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author ：yuanjian
 * @date ：Created in 2020/11/12 17:45
 * @description：
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Reference
    private SetmealService setmealService;

    @PostMapping("/upload")
    public Result upload (@RequestParam("imgFile") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
//        System.out.println("11222");
        String uuidFilename ="image/"+ UploadUtils.generateRandonFileName(originalFilename);
        AliyunUtils.uploadMultiPartFileToAliyun(file.getBytes(),uuidFilename);
        // 上传好阿里云图片之后 我们将图片存储到redis set 集合中
        redisTemplate.opsForSet().add(RedisConstant.ALL_SETMEAL_PIC_SET,uuidFilename);
        //将set 集合中所有key的值 添加到Redis中，并设置到期时间，从而达到删除垃圾图片的功能
        redisTemplate.opsForValue().set(RedisConstant.SINGLE_PIC+uuidFilename,uuidFilename,30, TimeUnit.SECONDS);
        //  将上传到阿里云的图片文件 保存在redis中
        return new Result(uuidFilename);//  一定要把阿里云上的文件名  回送给客户端 ，因为添加套餐时 需要存储到数据库的图片路径

    }

    @PostMapping("/findByPage")
    public Result findByPage(@RequestBody QueryPageBean pageBean) {
        return new Result(true, "查询成功!", setmealService.findByPage(pageBean));
    }

    @PostMapping("save")
    public Result save(@RequestBody SetmealDto setmealDto) {
        setmealService.save(setmealDto);
        return new Result(true);
    }

    @GetMapping("/findCheckGroupBySetmealId/{id}")
    public Result findCheckGroupBySetmealId(@PathVariable("id") Long setmealId) {
        return new Result(true, "查询成功!", setmealService.findCheckItemByCheckGroupId(setmealId));
    }

    @GetMapping("/clearOssImg")
    public void clearOssImg(){
        System.out.println("开始清理垃圾图片");
        setmealService.clearOssImg();
        System.out.println("清理垃圾图片成功");
    }

    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable("id") Long id){
        return new Result( setmealService.deleteById(id));
    }
}
